package com.dailyblue.project.estate.service.impl;

import com.dailyblue.project.estate.service.OllamaService;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Auther:Liu
 * @Testname:OllamaServiceImpl
 * @Date:2025/9/24 09:44
 */
@Service
public class OllamaServiceImpl implements OllamaService {
    @Resource
    private ChatClient ollamaChatClient;
    @Resource
    private VectorStore vectorStore;

    @Override
    public Flux<String> getOllama(String question) {
        //1.查询向量数据库
        List<Document> documents = vectorStore.similaritySearch(
                SearchRequest.builder()
                        .topK(3)
                        .similarityThreshold(0.5)
                        .query(question)
                        .build());
        String template= """
               请基于以下上下文回答问题:
               {documents}
               
               用户问题:{question}
               """;
        PromptTemplate promptTemplate = new PromptTemplate(template);
        promptTemplate.add("documents", documents.stream()
                .map(Document::getText)
                .collect(Collectors.joining("/n")));
        promptTemplate.add("question", question);
        //2.将问题抛给Ai
        return ollamaChatClient.prompt(promptTemplate.create()).user(question).stream().content();
    }
}
